<template>
	<view class="BusinessDetails">
		<kps-image-cutter @ok="onok" @cancel="oncancle" :url="url" :fixed="true" :blob="false" :maxWidth="100" :maxHeight="100"></kps-image-cutter>
		<view class="cont-libe">
			<view class="cont-left"> 店铺首图 </view>
			<view class="cont-right">
				<view class="cont-img-box" @click="chooseCutImage">
					<image class="cont-img" :src="info.picture" mode=""></image>
				</view>
			</view>
			
		</view>
		<view class="cont-libe">
			<view class="cont-left"> 店铺名称 </view>
			<view class="cont-right">
				<input class="cont-input" type="text" v-model="fromRequest.title" />
			</view>
		</view>
		<!-- <view class="cont-libe">
			<view class="cont-left"> 店铺类别 </view>
			<view class="cont-right" style="display: block; height: 60rpx; line-height: 60rpx;">
				<picker mode="multiSelector"  @columnchange="pickerColumnChange" :value="cateKey" :range="cateList" range-key="title">
					<view class="region">{{ cateName }}{{cateChildName}}</view>
				</picker>
			</view>
		</view> -->
		<view class="cont-libe">
			<view class="cont-left"> 店铺分类 </view>
			<view class="cont-right">
				{{info.cate}}
			</view>
		</view>
		<view class="cont-libe" v-if="info.status == -2">
			<view class="cont-left"> 开通年份 </view>
			<view class="cont-right" style="display: block;">
				<picker class="selPicker" @change="bindPickerChange" :value="itemName" :range="applyType" range-key="itemName">
					<view class="item">{{applyType[type].itemName}}</view>
				</picker>
                <view style="text-align: center;margin-top: 10rpx;">{{vaildDate}}</view>
			</view>
		</view>
		<view class="cont-libe" v-else>
			<view class="cont-left"> 有效年份 </view>
			<view class="cont-right">
				{{info.valid_date}}
			</view>
		</view>
		<view class="cont-libe-last">
			<view class="cont-libe-last-title"> 营业执照 </view>
			<view class="cont-libe-last-disc" style="margin-top: 20rpx;">
				<image v-if="info.status == -2 || info.status == -3" :src="info.logo" @click="chooseImage(0)"></image>
				<image v-else :src="info.logo" mode=""></image>
			</view>
		</view>
		<view class="cont-libe" style="border-bottom: 0;border-top: 2rpx solid #e5e5e5;;">
			<view class="cont-left"> 店铺地址 </view>
			<view class="cont-right address-aff" style="width: 506rpx;text-align: right;padding: 10rpx;">
				<!-- <input class="cont-input content-input-address" type="text" v-model="fromRequest.address" /> -->
				<view class="content-address" @click="getMapLocation()"> 点击获取经纬度 </view>
			</view>
		</view>
		<view class="cont-libe">
			<textarea class="cont-xxdz" v-model="fromRequest.address_details" placeholder-style="color:rgba(66,81,114,0.2);" placeholder="输入详细地址"/>
		</view>
		<view class="cont-libe">
			<view class="cont-left"> 联系人 </view>
			<view class="cont-right">
				<input class="cont-input" type="text" v-model="fromRequest.email" />
			</view>
		</view>
		<view class="cont-libe">
			<view class="cont-left"> 联系电话 </view>
			<view class="cont-right">
				<input class="cont-input" type="text" v-model="fromRequest.mobile" />
			</view>
		</view>
		<view class="cont-libe">
			<view class="cont-left"> 营业时间 </view>
			<view class="cont-right" style="width: auto;">
				<picker class="selPicker" mode="time" :value="fromRequest.start_business" start="00:00" end="23:59" @change="bindTimeChange">
					<view class="uni-input">{{fromRequest.start_business}}</view>
				</picker>
				<text style="margin: 0 20upx;">-</text>
				<picker class="selPicker" mode="time" :value="fromRequest.end_business" start="00:00" end="23:59" @change="bindEndTimeChange">
					<view class="uni-input">{{fromRequest.end_business}}</view>
				</picker>
				<!-- <time-picker ref="picker" @confirm="confirm" mode="hm">
					 <view @tap="show">开启</view>
				</time-picker> -->
			</view>
		</view>
		<view class="cont-libe" style="border: 0;">
			<view class="cont-left"> 店铺公告 </view>
		</view>
		<view class="cont-libe">
			<textarea class="cont-input-gg" placeholder-style="color:rgba(66,81,114,0.2);" value="" placeholder="输入店铺公告..." v-model="fromRequest.desc"/>
		</view>
		<view class="cont-libe-last">
			<view class="cont-libe-last-title"> 店铺相册 </view>
			<view class="cont-libe-last-disc">
			
				<view class="cont-libe-last-img"v-for="(item,index) in info.imgList" :key="index">
					<image class="cont-libe-last-img-close" src="../static/img/del-new.png" @click="imgListDelete(index)" mode=""></image>
					<image class="cont-libe-last-img-img" :src="item.thumb" mode="" @tap="previewImage(1)"
					:data-src="item.imgUrl" :data-id="index"></image>
				</view>
				
				<view class="cont-libe-last-upload" v-if="info.imgList.length < 15">
					<image @click="chooseImage(1)" src="../static/img/add_icon.png" mode=""></image>
				</view>
				
			</view>
		</view>
		<view class="flex-buttom" :style="'height:' + bottomHeight + 'rpx;'">
			<button @click="subForm"> 提交 </button>
		</view>
		
	</view>
</template>

<script>
	var _self;
	import serve from '../static/request.js';
	import storage from '../static/appkey.js';
	import common from '../static/jump.js';
	import kpsImageCutter from "@/components/ksp-image-cutter/ksp-image-cutter.vue";
	import uniRate from '@/components/uni-rate/uni-rate.vue';
	export default {
		components: {kpsImageCutter,uniRate},
		data() {
			return {
				id: 0,
				url:"",
				info: {
					id: 0,
					picture: '',
					title: '',
					name : '',
					mobile: '',
					cate: '',
					start_business: '',
					end_business: '',
					address: '',
					address_details: '',
					longitude: '',
					latitude: '',
					desc: '',
				},
				fromRequest:{
					appkey: uni.getStorageSync('appkey'),
					'access-token': uni.getStorageSync('access-token'),
					cover: '',
					title: '',
					email: '',
					mobile: '',
					cate_id: '',
					cate_pid: '',
					start_business: '',
					end_business: '',
					desc: '',
					logo: '',
					longitude:'',
					latitude:'',
					address_details: '',
					covers:'',
					openType: '',
					type: '',
				},
				isLogo : 0,
				catekey: [0, 0],
				cateList: [[],[]],
				cateName:'请选择',
				cateChildList: {},
				cateChildName: '',
				applyType: [],
				type: 0,
				previewList: [],
				vaildDate: '',
				bottomHeight: 110,/* 底部按钮高度，避免iPhonex导航黑条 */
			}
		},
		
		methods: {
			/* 获取店铺信息 */
			getInfo() {
				uni.showLoading({
					title: '加载中···',
					mask: true
				});
				serve.request({
					url: '/marketing/merchant/info',
					data: {
						appkey: uni.getStorageSync('appkey'),
						'access-token': uni.getStorageSync('access-token'),
						'local-city':uni.getStorageSync('localCity'),
						id: _self.id,
					}
				}).then(res => {
					if(res.code != 200) {
						uni.showToast({
							title: res.message,
							icon : 'none',
							success:function(){ 
								setTimeout(function () { 
									common.jump('return_one')
								}, 2000) 
							} 
						});
						return;
					}
					_self.info = res.data;
					_self.previewList = [];
					_self.info.imgList.forEach((it, kt) => {
						_self.previewList.push(it.imgUrl);
					});
					_self.fromRequest.id = res.data.id; //店铺ID
					_self.fromRequest.cate_id = res.data.cate_id;
					_self.fromRequest.cate_pid = res.data.cate_pid;
					_self.fromRequest.cover = res.data.picturePath; //店铺主图
					_self.fromRequest.title = res.data.title; //店铺标题
					_self.fromRequest.email = res.data.name;  //店铺联系人
					_self.fromRequest.mobile = res.data.mobile; //店铺联系电话
					_self.fromRequest.address_details = res.data.address_details; //店铺详细地址
					_self.fromRequest.longitude = res.data.longitude; //店铺经纬度
					_self.fromRequest.latitude = res.data.latitude; //店铺经纬度
					_self.fromRequest.desc = res.data.desc; //店铺公告
					_self.fromRequest.start_business = res.data.start_business; //营业时间
					_self.fromRequest.end_business = res.data.end_business; //营业时间
					if(_self.info.status == -2) {
						_self.fromRequest.openType = res.data.openType;
					}
					_self.fromRequest.type = res.data.type;
					// _self.getCateList();
					_self.getApplyType();
				});
			},
			//裁剪图片
			chooseCutImage() {
				uni.chooseImage({
					success: (res) => {
						// 设置url的值，显示控件
						_self.url = res.tempFilePaths[0];
					}
				});
			},
			//获取店铺分类
			getCateList() {
				serve.request({
					url: '/marketing/merchant/cate-list',
					data: {
						appkey: uni.getStorageSync('appkey'),
						'access-token': uni.getStorageSync('access-token'),
						cateId: 0,
					}
				}).then(res => {
					_self.cateList[0] = res.data;
					_self.cateList[1] = res.data[0].child;
					res.data.forEach((item,key) => {
						if(_self.fromRequest.cate_pid == item.id) {
							_self.catekey.splice(0, 1, key);
							_self.cateName = item.title;
							_self.cateList[1] = item.child;
							item.child.forEach((childItem, childKey) => {
								if(_self.fromRequest.cate_id == childItem.id) {
									_self.catekey.splice(1, 1, childKey);
									_self.cateChildName = childItem.title;
								}
							});
						}
						_self.$set(_self.cateChildList, key, item.child);
					});
					console.info(_self.catekey);
					// _self.catekey[0] = 0;
					// _self.catekey[1] = 0;
					_self.$forceUpdate();
				});
			},
			//选择店铺分类
			pickerColumnChange(e) {
				let changeColumn = e.detail.column;
				let selKey = e.detail.value;
				let selItem = _self.cateList[changeColumn][selKey];
				if(changeColumn == 0) {
					_self.catekey[0] = selItem.id;
					_self.catekey[1] = 0;
					_self.cateList[1] = _self.cateChildList[selKey];
					_self.cateName = selItem.title;
					let nextItem = _self.cateList[1][0];
					_self.fromRequest.cate_id = nextItem.id;
					_self.cateChildName = nextItem.title;
				} else if(changeColumn == 1) {
					_self.catekey[1] = selItem.id;
					_self.fromRequest.cate_id = selItem.id;
					_self.cateChildName = selItem.title;
				} 
				_self.$forceUpdate();
			},
			//获取开店类型
			getApplyType(){
				serve.request({
					url: '/marketing/apply/apply-type',
					data: {
						appkey: uni.getStorageSync('appkey'),
						type: _self.fromRequest.type
					}
				}).then(res => {
					_self.applyType = res.data;
					_self.type = 0;
					if(_self.fromRequest.openType != '') {
						_self.applyType.forEach((it, ik) => {
						    if(it.itemId == _self.fromRequest.openType) {
								_self.type = ik;
							}
						});
					}
					let applyTypeItem = _self.applyType[_self.type];
					_self.fromRequest.openType = applyTypeItem.itemId;
                    _self.vaildDate = applyTypeItem.validDate;
					_self.$forceUpdate();
				});
			},
			//选择开店类型
			bindPickerChange: function(e) {
				_self.type = e.target.value;
				let applyTypeItem = _self.applyType[_self.type];
				_self.fromRequest.openType = applyTypeItem.itemId;
				_self.vaildDate = applyTypeItem.validDate;
				_self.$forceUpdate();
			},
			//上传裁剪图片
			onok(ev) {
				_self.fromRequest.cover = ev.path;
				_self.url = "";
				let appkey = uni.getStorageSync('appkey');
				let accessToken = uni.getStorageSync('access-token');
				uni.uploadFile({
					url: serve.apiUrl() + '/v1/file/images?appkey=' + appkey + '&access-token='+accessToken,
					filePath: ev.path,
					name: 'file',
					formData: {},
					// 上传图片
					success: (uploadFileRes) => {
						let result = JSON.parse(uploadFileRes.data);
						if (result.code == 200) {
							_self.info.picture = result.data.imgUrl;
							_self.fromRequest.cover = result.data.imgPath;
						} else {
							uni.showToast({
								title: result.message,
								icon: 'none',
							})
						}
					}
				});
			},
			//取消裁剪图片
			oncancle() {
				_self.url = "";
			},
			// 获取经纬度
			getMapLocation(){
				uni.chooseLocation({
					'longitude': _self.fromRequest.longitude,
					'latitude': _self.fromRequest.latitude,
					success:(res)=> {
						_self.fromRequest.address_details = res.name;
						_self.fromRequest.longitude = res.longitude;
						_self.fromRequest.latitude = res.latitude;
						_self.$forceUpdate();
					},
					fail:()=>{
						uni.getSetting({
							success: (res) => {
								console.log(res);
								var status = res.authSetting;
								if(!status['scope.userLocation']){
									uni.showModal({
										title:"是否授权当前位置",
										content:"需要获取您的地理位置，请确认授权，否则地图功能将无法使用",
										success:(tip)=>{
											if(tip.confirm){
												uni.openSetting({
													success:(data)=>{
														if(data.authSetting['scope.userLocation']===true){
															uni.showToast({
																title:"授权成功",
																icon:"success",
																duration:1000
															})
															uni.chooseLocation({
																success: (res) => {
																	console.log("详细地址",res);
																}
															})
														}else{
															uni.showToast({
																title:"授权失败",
																icon:"none",
																duration:1000
															})
														}
													}
												})
											}
										}
									})
								}
							},
							fail: (res) => {
								uni.showToast({
									title:"调用授权窗口失败",
									icon:"none",
									duration:1000
								})
							}
						})
					}
				});
			},		
			//选择图片
			chooseImage(k) {
				let surplusNum = 1;
				if(k == 1) {
					if (_self.info.imgList.length >= 9) {
					    uni.showToast({
					        icon: "none",
					        title: "已上传9张图片，无法继续上传！",
					        mask: true,
					        duration: 1.5e3
					    });
					    return;
					}
					surplusNum = 9 - Number(_self.info.imgList.length);
				}
			    uni.chooseImage({
			        count: surplusNum,
			        sizeType: ['original', 'compressed'],
			        sourceType: ['album', 'camera'],
			        success: (chooseImageRes) => {
			            const tempFilePaths = chooseImageRes.tempFiles;
			            tempFilePaths.forEach((file, key) => {
			                const maxSize = 10 * 1024 * 1024;
			                if (file.size > maxSize) {
			                    uni.showToast({
			                        icon: "none",
			                        title: "文件不能大于10兆",
			                        mask: true,
			                        duration: 1.5e3
			                    });
			                    return;
			                } else {
								if(k == 1) {
									let temp = {
										isUpload: 0,
										thumb: file.path,
										imgUrl: file.path,
										imgPath: ''
									};
									_self.info.imgList.push(temp);
									_self.previewList = [];
									_self.info.imgList.forEach((it, kt) => {
										_self.previewList.push(it.imgUrl);
									});
								} else {
									_self.isLogo = 1;
									_self.info.logo = file.path;
								}
			                }
			            });
			            _self.$forceUpdate();
			        }
			    });
			},	
			// 删除上传的图片
			imgListDelete(key){
				_self.info.imgList.splice(key, 1);
				_self.previewList = [];
				_self.info.imgList.forEach((it, kt) => {
					_self.previewList.push(it.imgUrl);
				});
			},
			//预览图片
			previewImage: function(e) {
			    var current = e.target.dataset.src;
			    var k = e.target.dataset.id;
			    uni.previewImage({
			        current: current,
			        urls: _self.previewList
			    });
			    return;
			},
			//上传图片
			async uploadFileFun(file) {
				let appkey = uni.getStorageSync('appkey');
				let accessToken = uni.getStorageSync('access-token');
				return new Promise((resolve, reject) => {
					uni.uploadFile({
						url: serve.apiUrl() + '/v1/file/images?appkey=' + appkey+'&access-token='+accessToken,
						filePath: file,
						name: 'file',
						formData: {},
						success: (uploadFileRes) => {
							let result = JSON.parse(uploadFileRes.data);
							if (result.code == 200) {
								resolve(result.data.imgPath);
								return result.data.imgPath;
							} else {
								uni.showToast({
									title: result.message,
									icon: 'none',
								});
								reject(false);
								return false;
							}
						}
					});
				});
			},
			//提交表单
			async subForm() {
				uni.showLoading({
					title: '图片上传···',
					mask: true
				});
				_self.fromRequest.covers = '';
				if(_self.isLogo == 1) {
					let resultTemp = await _self.uploadFileFun(_self.info.logo);
					_self.fromRequest.logo = resultTemp;
					_self.isLogo = 0;
				}
				for(var i=0;i<_self.info.imgList.length;i++){
					let val = _self.info.imgList[i];
					if(val.imgPath == '') {
						let resultTemp = await _self.uploadFileFun(val.thumb);
						val.imgPath = resultTemp;
						_self.fromRequest.covers += resultTemp + ';';
					} else {
						_self.fromRequest.covers += val.imgPath + ';';
					}
				}
				uni.hideLoading();
				serve.request({
					url: '/marketing/merchant/update',
					data: _self.fromRequest
				}, 'POST').then(res => {
					uni.showToast({
						title: res.message,
						icon: 'none',
						success() {
							if(res.code == 200){
								setTimeout(function () {
									uni.redirectTo({
									    url: '/merchant/detail?id='+_self.fromRequest.id
									});
								}, 2000) 
							}
						}
					});
				});
			},
			bindTimeChange: function(e){
				_self.fromRequest.start_business = e.detail.value;
			},
			bindEndTimeChange: function(e){
				_self.fromRequest.end_business = e.detail.value;
			},
			jump(jump_type, jump_link){
				common.jump(jump_type, jump_link);
			}
		},
		onLoad(options) {
			_self = this;
			if(uni.getSystemInfoSync().safeAreaInsets.top > 20){
				_self.bottomHeight = 150;
			}
			_self.id = options.id || 0;
			if(_self.id == 0) {
				uni.showToast({
					title: "错误的访问方式",
					icon : 'none',
					success:function(){ 
						setTimeout(function () { 
							common.jump('return_one')
						}, 2000) 
					} 
				});
				return;
			}
			_self.getInfo();
		},
	}
</script>

<style scoped lang="scss">
	.BusinessDetails {
		padding-bottom: 100upx;
		width: 100vw;
		background-color: #FFFFFF;
		font-size: 32rpx;
		color: #333333;
	}
	.cont-libe{
		margin-left: 32rpx;
		display: flex;
		align-items: center;
		width: 676rpx;
		// margin-top: 20rpx;
		padding: 30rpx 0;
		justify-content: space-between;
		border-bottom: 2rpx solid #e5e5e5;
	}
	.cont-input-gg{
		width: 100%;
		text-align: left;
		height: 150rpx;
		line-height: 40rpx;
		padding: 5rpx;
		border: 1px solid #ccc;
	}
	.cont-left{
		width: 140rpx;
		height: 60rpx;
		line-height: 60rpx;
	}
	.cont-right{
		position: relative;
		display: flex;align-items: center;
		width: 446rpx;
		text-align: right;
		input {
			    border: 1px solid #ccc;
			    padding-right: 10rpx;
		}
		.selPicker{
			padding: 0 10rpx;
			border: 1px solid #cccc;
			height: 80rpx;
			line-height: 80rpx;
			text-align: center;
			letter-spacing: 5rpx;
		}
	}
	// .cont-right::after{
	// 	position: absolute;
	// 	right: 30upx;
	// 	top: 60upx;
	// 	content: '';
	// 	border: 1upx solid rgba(57, 72, 107, 0.5);
	// 	border-width: 0 3upx 3upx 0;
	// 	padding: 6upx;
	// 	transform: rotate(-45deg);
	// 	-webkit-transform: rotate(-45deg);
	// }
	
	.cont-xxdz{
		height: 50rpx;
		width: 506rpx;
		line-height: 50rpx;
		font-size: 30rpx;
	}
	
	.cont-input{
		// border: 2rpx solid #e5e5e5;
		    width: 446rpx;
		    padding-left: 20rpx;
		    height: 80rpx;
		    border-radius: 4rpx;
		    font-size: 30rpx;
	}
	
	.content-input-address{
		    width: 340rpx;
		    height: 100rpx;
		    line-height: 50rpx;
			font-size: 28rpx;
	}
	.content-address{
		position: relative;
		height: 60rpx;
		width: 100%;
		color: #EB5938;
	}
	
	


	
	.cont-img-box{
		position: relative;
		width: 240rpx;
		height: 240rpx;
	}
	.cont-close{
		position: absolute;
		width: 48rpx;height: 48rpx;
		top: -24rpx;right: -24rpx;
	}
	.cont-img{
		width: 240rpx;
		height: 240rpx;
	}
	
	.cont-libe-last{
		width: 676rpx;
		margin-top: 20rpx;
		padding: 20rpx 0;
		margin-left: 32rpx;
		margin-bottom: 80rpx;
	}
	
	.cont-libe-last-title{
		    width: 100%;
		    line-height: 44rpx;
	}

	/* start--清除浮动 */
	.cont-libe-last-disc:after {
		/* #ifndef APP-NVUE */
		content: '';
		/* #endif */
		display: table;
		clear: both;
	}
	/* end--清除浮动 */
	
	.cont-libe-last-img{
		    float: left;
		    width: 200rpx;
		    height: 200rpx;
		    position: relative;
		    padding: 12rpx;
	}
	.cont-libe-last-img-close{width: 40rpx;height: 40rpx;position: absolute;top: -6rpx;right: -6rpx;}
	.cont-libe-last-img-img{width: 100%;height: 100%;}
	.cont-libe-last-upload{float: left;width: 200rpx;height: 200rpx;padding: 12rpx;}
	.cont-libe-last-upload image{width: 100%;height: 100%;}
	


	.flex-buttom{
		position: fixed;
		bottom: 0rpx;
		width: 100vw;
		height: 110rpx;
		background-color: #FFFFFF;
		z-index: 9;
		button{
			    width: 640rpx;
				height: 88rpx;
				border-radius: 44rpx;
			    font-size: 32rpx;
			    color: #ffffff;
			    background: #EB5938;
			    margin-top: 10rpx;
		}
	}
	
	
	
</style>
